package com.hnevc.listviewdemo;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import java.io.File;
import java.io.IOException;

public class AddFoodActivity extends AppCompatActivity {

    public static final int TAKE_PHOTO = 101;
    private Uri imageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_food);
    }

    public void takePhoto(View view) throws IOException {
        //三个步骤
        //1 准备照片存储的文件 uri
        File file = new File(getExternalCacheDir(),"image.jpg");
        if(file.exists()){
            //如果已经存在，那么就先删除它
            // 然后再创建file
            file.delete();
        }
        file.createNewFile();

        if(Build.VERSION.SDK_INT >= 24){
            imageUri = FileProvider.getUriForFile(this, "com.hnevc.listviewdemo.fileprovider", file);
        }else{
            imageUri = Uri.fromFile(file);
        }

        //2 启动拍照Activity
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //照相activity，将数据输出到imageuri
        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
        startActivityForResult(intent, TAKE_PHOTO);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       // 3 获取照片文件中的数据，显示在ImageView中
        if(resultCode == RESULT_OK){//判断是否正确返回
            //获取imageUri的文件路径
            String path = imageUri.getPath();
            //将图片文件，转换为bitmap
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            //获取显示图片的视图控件
            ImageView imageView = (ImageView) findViewById(R.id.id_iv_foodPic);
            //将bitmap显示在视图控件中
            imageView.setImageBitmap(bitmap);
        }
    }
}
